package main

import (
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"os"
	"path"
	"regexp"
	"strings"
)

type Song struct {
	id     string // ID
	title  string // 歌名
	singer string // 歌手
	album  string // 专辑
	url    string // 下载连接
}

var albumPattern, titlePattern, singerPattern, urlPattern *regexp.Regexp

func init() {
	albumPattern = regexp.MustCompile("album_name: \"(.*)\"")
	titlePattern = regexp.MustCompile("song_title: \"(.*)\"")
	singerPattern = regexp.MustCompile("singer_name: \"(.*)\"")
	urlPattern = regexp.MustCompile("(/data/music/file\\?link=http.*)\"  id=")
}

func (self *Song) String() string {
	return fmt.Sprintf("Song{id: %s, title: %s, singer: %s, album: %s, url: %s", self.id, self.title, self.singer, self.album, self.url)
}

func newSong(id string) *Song {
	url := fmt.Sprintf("http://music.baidu.com/song/%s/download", id)
	html := fetchHtml(url, cookie)
	if len(html) > 0 {
		song := &Song{id: id, title: findAllMatch(html, titlePattern)[0], album: findAllMatch(html, albumPattern)[0], singer: findAllMatch(html, singerPattern)[0], url: findAllMatch(html, urlPattern)[0]}
		return song
	} else {
		log.Printf("fetch URL: %s err.\n", url)
	}
	return nil
}

func (self *Song) download() (err error) {
	log.Printf("开始下载 %s\n", self.title)
	url := "http://music.baidu.com" + strings.TrimSpace(self.url)
	singer := strings.TrimSpace(self.singer)
	album := strings.TrimSpace(self.album)
	title := strings.TrimSpace(self.title)
	filename := title + ".mp3"
	fileDir := path.Join(downloadPath, singer, album)
	filePath := path.Join(fileDir, filename)

	if _, err = os.Stat(filePath); os.IsNotExist(err) {
		resp, e2 := http.Get(url)

		if e2 != nil {
			log.Println("Failed to download.", e2)
			err = e2
			return
		}

		defer resp.Body.Close()

		os.MkdirAll(fileDir, 0777)
		data, _ := ioutil.ReadAll(resp.Body)
		ioutil.WriteFile(filePath, data, 0644)
		log.Printf("完成下载 %s\n", self.title)
	} else {
		log.Println(filePath + " 已存在.")
	}
	return
}
